package Engine.Model
{
	import Engine.Manager.EngineManager;
	import GameMain.Game;
	
	import GameMain.Macro.MacroEvent;
	
	import Interface.Model.ISocketManager;
	
	import library.SocketData.SocketData;
	
	public class SocketManager implements ISocketManager
	{
		
		
		private var _socket:GameSocket;
		private var _socket2:GameSocket; //游戏对战中心的Socket
		private var _socketCode:int = 0;
		private var _socketEntityID:int = 0;
		
		
		public function SocketManager()
		{
			this._socket = new GameSocket("Main:");
			this._socket2 = new GameSocket("Game:");
			this._socket2.setConnectFun(this.onSocket2Connected);
			EngineManager.eventMgr.registerEvent(MacroEvent.MSG_FROM_SERVER_SOCKET2,connectSocket2);
		}
		
		
		public function sendMessageData(msgID:int,msgData:*):void
		{
			if(!this._socket.connected)
				return;
			if(this._socket2.connected)
			{
				this._socket2.sendMessageData(msgID,msgData);
			}
			else
			{
				this._socket.sendMessageData(msgID,msgData);
			}
		}
		
		public function connectSocket(ip:String,port:int):void
		{
			if(this._socket.connected)
				return;
			this._socket.connect(ip,port);
		}
		
		public function setConnectFun(fun:Function):void
		{
			this._socket.setConnectFun(fun);
		}
		
		public function setDisConnectFun(fun:Function):void
		{
			this._socket.setDisConnectFun(fun);
		}
		
		public function disconnected():void
		{
			this._socket.close();
			this._socket2.close();
		}
		
		private function onSocket2Connected():void
		{
			var data:SocketData = new SocketData();
			data.writeInt16(this._socketCode);
			data.writeInt16(this._socketEntityID);
			EngineManager.logPrint.printLog("Socket2 connect Success Send",this._socketCode,this._socketEntityID);
			this.sendMessageData(2,data);
		}
		
		private function connectSocket2(data:SocketData):void
		{
			var ip:String = "";
			ip = String(data.readUnsignedByte())+"."+String(data.readUnsignedByte())+"."+String(data.readUnsignedByte())+"."+String(data.readUnsignedByte());
			var port:int = data.readInt16();
			this._socketCode = data.readUnsignedShort();
			this._socketEntityID = data.readUnsignedShort();
			Game.ownPlayer.setEntityID(this._socketEntityID);
			Game.EntityMgr.resetEntity();
			this._socket2.connect(ip,port);
		}
	}
}